import { Button, Image, Spin } from "antd";
import { useEffect, FC, useCallback, useState, useRef } from "react";
import "./ImageMore.css";
type UrlObj = {
  id: number;
  url: string;
};
export const ImageMore: FC = () => {
  const imgNum = 6;
  const groupArr = Array.from({ length: imgNum }).map((_, index) => ({
    id: index,
    url: "",
  }));
  const [imgUrls, setImgUrls] = useState<UrlObj[]>([...groupArr]);
  const [spinVisible, setSpinVisible] = useState<boolean>(false); //加载遮罩
  const workerRef = useRef<Worker | null>(null);
  const imgUrlsRef = useRef([...groupArr]);
  useEffect(() => {
    console.log("执行");

    // getImageList();
    advance();
  }, []);
  const advance = useCallback(() => {
    const arr = imgUrls.map(
      (_, index) =>
        `https://api.vvhan.com/api/wallpaper/views?info=${
          new Date().getTime() + index
        }`
    );
    workerRef.current = new Worker(new URL("worker.js", import.meta.url));

    workerRef.current.postMessage(arr);
    workerRef.current.onmessage = function ({ data: { data, id } }) {
      const img_url = window.URL.createObjectURL(data);
      imgUrlsRef.current = imgUrlsRef.current.map((item) =>
        item.id === id ? { ...item, url: img_url } : item
      );
      console.log("img_url", img_url, "id", id);
      setImgUrls(imgUrlsRef.current);
      if (id === imgNum - 1) {
        setSpinVisible(false);
      }
    };
  }, []);

  const getImageList = useCallback(() => {
    imgUrlsRef.current=[...groupArr]

    setSpinVisible(true);
    advance();
  }, []);
  const renderImage = useCallback(() => {
    return imgUrls.map((item, i) => (
      <div key={i} className="image-ui">
        <Image
          width={"100%"}
          height={"100%"}
          src={item.url || "error"}
          fallback=""
        ></Image>
      </div>
    ));
  }, [imgUrls]);

  return (
    <>
      <div className="layout-header">
        <h1>加载大量图片</h1>
        <div>
          <Button
            type="primary"
            onClick={() => {
              getImageList();
            }}
          >
            更新图片
          </Button>
        </div>
      </div>
      <div className="layout-body">
        <Spin spinning={spinVisible} tip="Loading...">
          {renderImage()}
        </Spin>
      </div>
    </>
  );
};
